package net.sf.rose.redis;

import net.sf.rose.boot.BootStrap;
import net.sf.rose.jdbc.DBUtils;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.spring.ApplicationUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis连接池工具类
 */
public class RedisPoolUtils {

	private static JedisPool jedisPool = null;

	private static boolean inUse = false;

	/**
	 * 初始化Redis连接池
	 * 从数据库中查连接池的配置
	 */
	public static void initial() {
		Service service = new Service();
		// service.getTableBean(RedisPoolBean.class);
		String val = BootStrap.getProjectName();
		RedisPoolBean bean = DBUtils.getBean(service, RedisPoolBean.class, "projectName", val);
		service.close();
		if (bean != null) {
			// 创建jedis池配置实例
			JedisPoolConfig config = new JedisPoolConfig();
			// 设置池配置项值
			config.setMaxTotal(bean.getMaxActive());
			config.setMaxIdle(bean.getMaxIdle());
			config.setMaxWaitMillis(bean.getMaxWait());
			config.setTestOnBorrow(bean.getTestOnBorrow() == 1 ? true : false);
			config.setTestOnReturn(bean.getTestOnReturn() == 1 ? true : false);
			// 根据配置实例化jedis池
			jedisPool = new JedisPool(config, bean.getIp(), bean.getPort(), bean.getTimeout(), bean.getPassword());
			inUse = true;
			System.out.println("Jedis线程池被成功初始化...");
		}
	}

	/**
	 * 获得连接，用户自己关闭
	 * @return Jedis
	 */
	public static Jedis getJedis() {
		return jedisPool.getResource();
	}

	// 关闭池
	public static void close() {
		if (jedisPool != null) {
			jedisPool.close();
		}
	}

	/**
	 * 判断缓存是否启用
	 * @return
	 */
	public static boolean inUse() {
		return inUse;
	}
}